package blog.gui;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import blog.ConstString;
import blog.SysRuntime;
import blog.controller.ConstAction;
import blog.controller.ConstGui;
import blog.util.StringUtils;

public class VerifyUserGui extends Form implements IBaseGui, CommandListener {
	
	public static final int TYPE_EXIT = 1;
	public static final int TYPE_BACK = 2;
	
	Command cmdConfirm = new Command(ConstString.CMD_REGIST_USER, Command.OK, 0);
	Command cmdExit = new Command(ConstString.CMD_EXIT, Command.EXIT, 0);
	Command cmdBack = new Command(ConstString.CMD_BACK, Command.BACK, 0);
	
	TextField registCode;
	TextField email;
	
	public VerifyUserGui(int type) {
		super(ConstString.GUI_TITLE_USER_VERIFY);
		this.setCommandListener(this);
		this.addCommand(cmdConfirm);
		if ( type==TYPE_BACK )
		{
			this.addCommand(cmdBack);
		}
		else if ( type==TYPE_EXIT)
		{
			this.addCommand(cmdExit);
		}
		this.append( new StringItem("", ConstString.GUI_VERIFY_USER_PROMPT, Item.PLAIN));
		
		registCode = new TextField( ConstString.GUI_VERIFY_USER_REGIST_CODE, "", 64, TextField.ANY );
		email = new TextField( ConstString.GUI_VERIFY_USER_EMAIL_ADDRESS, "", 64, TextField.EMAILADDR);
		
		append(registCode);
		append(email);
	}

	public int getIdentify() {
		return ConstGui.GUI_ID_VERIFY_USER;
	}

	public void notifyChanged(Object param) {
	}

	public void commandAction(Command cmd, Displayable arg1) {
		if ( cmd==cmdExit )
		{
			SysRuntime.midlet.destroyApp(true);
		}
		else if ( cmd==cmdConfirm )
		{
			if ( !checkOk() )
			{
				return;
			}
			SysRuntime.actionManager.addAction(this, ConstAction.ACT_VERIFY_USER, new String[]{registCode.getString(), email.getString()} );
		}
		else if ( cmd==cmdBack )
		{
			SysRuntime.guiManager.back( );
		}
	}
	
	private boolean checkOk()
	{
		String str = registCode.getString();
		if ( str==null || str.length()==0 )
		{
			Alert alert = new Alert( ConstString.GUI_TITLE_PROMPT, StringUtils.combin( ConstString.PROMPT_NO_EMPTY, ConstString.GUI_VERIFY_USER_REGIST_CODE), null, AlertType.WARNING);
			alert.setTimeout(5000);
			SysRuntime.guiManager.showAlert(alert, true);
			return false;
		}
		
		str = email.getString();
		if ( str==null || str.length()==0 )
		{
			Alert alert = new Alert( ConstString.GUI_TITLE_PROMPT, StringUtils.combin( ConstString.PROMPT_NO_EMPTY, ConstString.GUI_VERIFY_USER_EMAIL_ADDRESS), null, AlertType.WARNING);
			alert.setTimeout(5000);
			SysRuntime.guiManager.showAlert(alert, true);
			return false;
		}
		return true;
	}
}